package com.itheima.tlias.interceptor;

import com.itheima.tlias.utils.BaseContext;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 16 4月 2025 10:32
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("[TokenInterceptor]目标资源拦截器，目标资源方法执行前的逻辑");
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是 Controller 方法，直接放行 // 非动态方法，直接放行
            return true;
        }
        if ( "/login".equals(request.getRequestURI())){
            log.info("[TokenInterceptor]目标资源拦截器，登录请求放行");
            return true;
        }
        //获取请求头
        String token = request.getHeader("token");
        //校验token是否为空
        if (!StringUtils.hasLength(token)){
        //如果为空设置响应码401返回false
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //不为空校验token
        try {
            Claims claims = jwtUtils.parseJWT(token);
            Object id = claims.get("id");
            Integer i = Integer.valueOf(String.valueOf(id));
            log.info("用户id是，{}",i);
            //设置本地线程变量
            BaseContext.set(i);
        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        log.info("登录校验成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("[TokenInterceptor]目标资源拦截器，目标资源方法执行后的逻辑");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("[TokenInterceptor]目标资源拦截器，视图渲染完成后的逻辑");
        BaseContext.remove();

    }
}
